<template>
  <el-container>
    <!--头部区域-->
    <el-header class="el-header" style="height: 60px">
      <el-container>
        <!--logo图片-->
        <div>
          <el-image src="img/buy.png" class="header-img"></el-image>
          <div style="margin-top: 20px;float: left;float: right;color: white;font-family: 微软雅黑">
            超市账单管理系统
          </div>
        </div>
        <!--顶部导航-->
        <el-dropdown style="margin-left: auto;padding-right: 20px">
          <span class="el-dropdown-link">
            <img :src="loginUser.headUrl" class="face"/>
            <div class="text">
              {{loginUser.userName}}:{{loginUser.userCode}}, 欢迎您
              <i class="el-icon-arrow-down el-icon--right"></i>
            </div>
          </span>
          <template #dropdown>
            <el-dropdown-item @click="handleEdit">个人资料</el-dropdown-item>
            <el-dropdown-item divided @click="showEditPwdView">密码修改</el-dropdown-item>
            <el-dropdown-item divided @click="logout">注销退出</el-dropdown-item>
          </template>
        </el-dropdown>
      </el-container>
    </el-header>

    <el-container style="height: 650px; border: 1px solid #eee">
      <!--侧边栏区域-->
      <el-aside width="200px" style="background-color: rgb(238, 241, 246)" id="aside">
        <side-menu @menuClick="toHtml"></side-menu>
      </el-aside>
      <!--主区域-->
      <el-container>
        <el-main>
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </el-container>
    </el-container>

    <!-- 个人资料 -->
    <el-dialog title="个人资料" v-model="userEditFormVisible">
      <el-form :model="userEditForm" :rules="userEditRules" ref="userEditRef">
        <el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth">
          <el-input v-model="userEditForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" :label-width="formLabelWidth">
          <el-radio v-model="userEditForm.gender" label="1">男</el-radio>
          <el-radio v-model="userEditForm.gender" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday" :label-width="formLabelWidth">
          <el-date-picker
              v-model="userEditForm.birthday"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth">
          <el-input v-model="userEditForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="userEditForm.address"></el-input>
        </el-form-item>
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-upload
              size="mini"
              class="avatar-uploader"
              :action="server_url() + '/user/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="userEditForm.headUrl"
                :src="requestUrl"
                class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>

          </el-upload>
        </el-form-item>

<!--        <el-form-item label="头像地址" :label-width="formLabelWidth">-->
<!--          <el-input :value="requestUrl" disabled></el-input>-->
<!--        </el-form-item>-->


      </el-form>
      <template #footer>
        <el-button @click="userEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="doUpdateUser">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 密码修改 -->
    <el-dialog title="密码修改" v-model="pwdEditFormVisible">
      <el-form :model="pwdEditForm" :rules="pwdEditRules" ref="pwdEditFormRef">
        <el-form-item label="旧密码" prop="userPassword" :label-width="formLabelWidth">
          <el-input type="password" v-model="pwdEditForm.userPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd" :label-width="formLabelWidth">
          <el-input type="password" v-model="pwdEditForm.newPwd"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmNewPwd" :label-width="formLabelWidth">
          <el-input type="password" v-model="pwdEditForm.confirmNewPwd"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pwdEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="doUpdatePwd">确 定</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>

import {computed, onMounted, reactive, ref} from "vue";
import {server_url} from "@/utils/server";
import {getByUserCode, updateUser, updatePassword} from "@/api/user";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import SideMenu from "@/views/homepage/SideMenu.vue";

export default {
  name: 'HomePage',
  methods: {
    server_url() {
      return server_url
    }
  },
  components: {
    SideMenu
  },
  setup() {

    const router = useRouter()
    const iframeSrc = ref('welcome.html')
    const formLabelWidth = ref('120px')
    const userEditFormVisible = ref(false)
    const userEditForm = reactive({
      userName: '',
      gender: '1',
      birthday: '',
      phone: '',
      address: '',
      headUrl: '',
      id: null
    })
    const userEditRef = ref(false)
    
    const userEditRules = {
      userName: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名称长度在 2 到 20 个字符', trigger: 'blur' }
      ]
    }

    const showEditForm = reactive({
      userCode: '',
      userName: '',
      gender: '1',
      birthday: '',
      phone: '',
      address: '',
      headUrl: 'img/face.png',
      id: null
    })

    const pwdEditFormVisible = ref(false)
    const pwdEditForm = reactive({
      userPassword: '',
      newPwd: '',
      confirmNewPwd: ''
    })
    const pwdEditFormRef = ref(null)
    const pwdEditRules = {
      userPassword: [{
        required: true,
        message: '请输入旧密码',
        trigger: 'blur'
      }],
      newPwd: [{
        required: true,
        message: '请输入新密码',
        trigger: 'blur'
      }],
      confirmNewPwd: [{
        required: true,
        message: '请输入确认密码',
        trigger: 'blur'
      }]
    }
    const loginUser = reactive({
      role: {roleName: ""},
      userName: "",
      userCode: "",
      headUrl: ""
    })


    // const loginUserStr = localStorage.getItem('loginUser');
    // const {userCode} = JSON.parse(loginUserStr);
    // const user = getByUserCode(userCode)

    // console.log("requestUrl=" + requestUrl)
    console.log("roleName=" + loginUser.role)

    const requestUrl = computed(() => {
      console.log("requestUrl=" + server_url + userEditForm.headUrl)
      return userEditForm.headUrl
          ? server_url.replace(/\/$/, '') + userEditForm.headUrl
          : ''
    })

    function toHtml(page) {
      let time = new Date().getTime()
      iframeSrc.value = page + "?t=" + time
    }

// async function showEditUserView() {
//   userEditFormVisible.value = true
//   const loginUserStr = localStorage.getItem("loginUser")
//   console.log("loginUserStr=" + loginUserStr)
//
//   const { userCode } = JSON.parse(loginUserStr)
//   console.log("loginUser=" + userCode)
//
//   try {
//     const res = await getByUserCode(userCode)
//     const currentUser = res
//     console.log("当前用户信息：", currentUser)
//
//     userEditForm.userName = currentUser.userName || ''
//     userEditForm.gender = currentUser.gender?.toString() || '1'
//     userEditForm.birthday = currentUser.birthday || ''
//     userEditForm.phone = currentUser.phone || ''
//     userEditForm.address = currentUser.address || ''
//     userEditForm.headUrl = currentUser.headUrl || 'img/face.png'
//     userEditForm.id = currentUser.id
//
//     console.log("userEditForm=", userEditForm)
//   } catch (error) {
//     console.error("获取用户信息失败：", error)
//   }
// }

    const handleEdit = async () => {
      const loginUserStr = localStorage.getItem('loginUser');
      const {userCode} = JSON.parse(loginUserStr);

      const res = await getByUserCode(userCode)
      const currentUser = res.data
      console.log("当前用户信息：", currentUser)

      userEditForm.userName = currentUser.userName || ''
      userEditForm.gender = currentUser.gender?.toString() || '1'
      
      // 处理生日数据
      if (currentUser.birthday) {
        if (typeof currentUser.birthday === 'string') {
          // 如果是字符串，处理可能的格式
          let dateStr = currentUser.birthday;
          
          // 如果包含时间信息，只取日期部分
          if (dateStr.includes(' ')) {
            dateStr = dateStr.split(' ')[0];
          }
          if (dateStr.includes('T')) {
            dateStr = dateStr.split('T')[0];
          }
          
          // 验证并标准化日期格式
          const date = new Date(dateStr);
          if (!isNaN(date.getTime())) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            userEditForm.birthday = `${year}-${month}-${day}`;
          } else {
            userEditForm.birthday = dateStr; // 保持原格式，让用户选择
          }
        } else {
          // 如果是Date对象，转换为YYYY-MM-DD格式
          const date = new Date(currentUser.birthday);
          if (!isNaN(date.getTime())) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            userEditForm.birthday = `${year}-${month}-${day}`;
          } else {
            userEditForm.birthday = '';
          }
        }
      } else {
        userEditForm.birthday = '';
      }
      
      userEditForm.phone = currentUser.phone || ''
      userEditForm.address = currentUser.address || ''
      userEditForm.headUrl = currentUser.headUrl || 'img/face.png'
      userEditForm.id = currentUser.id

      console.log("处理后的userEditForm:", userEditForm)
      console.log("生日字段值:", userEditForm.birthday)

      userEditFormVisible.value = true;
    };


    function handleAvatarSuccess(res) {
      userEditForm.headUrl = res.data
      loginUser.headUrl = res.data
    }

    function beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }

    function doUpdateUser() {
      // 表单验证
      if (!userEditRef.value) {
        console.log('表单引用不存在，直接提交');
        submitUserUpdate();
        return;
      }
      
      userEditRef.value.validate((valid) => {
        if (valid) {
          submitUserUpdate();
        } else {
          ElMessage.error('请检查输入信息');
        }
      });
    }
    
    function submitUserUpdate() {
      const updateData = { ...userEditForm };
      
      // 确保日期格式正确
      if (updateData.birthday) {
        // 如果birthday是Date对象，转换为字符串
        if (updateData.birthday instanceof Date) {
          const year = updateData.birthday.getFullYear();
          const month = String(updateData.birthday.getMonth() + 1).padStart(2, '0');
          const day = String(updateData.birthday.getDate()).padStart(2, '0');
          updateData.birthday = `${year}-${month}-${day}`;
        }
        // 如果birthday已经是字符串，检查格式（但要宽松一些）
        else if (typeof updateData.birthday === 'string') {
          // 如果日期字符串包含时间信息，只取日期部分
          if (updateData.birthday.includes(' ') || updateData.birthday.includes('T')) {
            const datePart = updateData.birthday.split(' ')[0].split('T')[0];
            updateData.birthday = datePart;
          }
          
          // 验证日期格式是否为YYYY-MM-DD
          const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
          if (!dateRegex.test(updateData.birthday)) {
            // 尝试转换其他常见格式
            const date = new Date(updateData.birthday);
            if (!isNaN(date.getTime())) {
              // 如果能成功解析为有效日期，转换为标准格式
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0');
              const day = String(date.getDate()).padStart(2, '0');
              updateData.birthday = `${year}-${month}-${day}`;
            } else {
              console.warn('日期格式不正确:', updateData.birthday);
              ElMessage.error('请选择正确的出生日期');
              return;
            }
          }
        }
      } else {
        // 如果生日为空，设置为null
        updateData.birthday = null;
      }
      
      console.log('准备提交的数据:', updateData);
      
      updateUser(updateData).then(res => {
        console.log('完整 res 对象：', res)
        console.log('res.data：', res.data)

        if (res.data.flag) {
          ElMessage.success(res.data.message || '更新成功')
          userEditFormVisible.value = false
          loginUser.headUrl = userEditForm.headUrl
          loginUser.userName = userEditForm.userName
          
          // 更新localStorage中的用户信息
          const loginUserStr = localStorage.getItem('loginUser');
          if (loginUserStr) {
            const loginUserData = JSON.parse(loginUserStr);
            loginUserData.userName = userEditForm.userName;
            loginUserData.headUrl = userEditForm.headUrl;
            localStorage.setItem('loginUser', JSON.stringify(loginUserData));
          }
        } else {
          ElMessage.error(res.data.message || '更新失败')
        }
      }).catch(err => {
        console.error('更新异常', err)
        ElMessage.error('更新异常：' + (err.message || '未知错误'))
      })
    }

    function showEditPwdView() {
      pwdEditFormVisible.value = true
    }

    function doUpdatePwd() {
      if (!pwdEditFormRef.value) {
        console.error('密码修改表单引用不存在');
        return;
      }

      pwdEditFormRef.value.validate(async (valid) => {
        if (!valid) return;

        // 验证新密码和确认密码是否一致
        if (pwdEditForm.newPwd !== pwdEditForm.confirmNewPwd) {
          ElMessage.warning("新密码和确认密码不一致,请重新输入");
          return;
        }

        try {
          // 获取当前登录用户信息
          const loginUserStr = localStorage.getItem('loginUser');
          const currentUser = JSON.parse(loginUserStr);
          
          // 调用密码修改API
          const passwordData = {
            userId: currentUser.id,
            oldPassword: pwdEditForm.userPassword,
            newPassword: pwdEditForm.newPwd
          };

          const res = await updatePassword(passwordData);
          
          if (res.data.flag) {
            ElMessage.success(res.data.message || "密码修改成功，请重新登录");
            pwdEditFormVisible.value = false;
            
            // 清空密码表单
            pwdEditForm.userPassword = '';
            pwdEditForm.newPwd = '';
            pwdEditForm.confirmNewPwd = '';
            
            // 退出登录
            logout();
          } else {
            ElMessage.error(res.data.message || "密码修改失败");
          }
        } catch (error) {
          console.error('密码修改异常：', error);
          ElMessage.error("密码修改异常：" + (error.message || "未知错误"));
        }
      });
    }

// function doUpdatePwd(formName) {
//   // 这里需要用ref获取表单实例，建议用ref="pwdEditForm"并用defineExpose暴露
//   // 这里假设你已正确获取表单实例
//   // 伪代码如下，实际请根据你的表单ref获取方式调整
//   pwdEditFormRef.value.validate((valid) => {
//
//   })
//   // 这里只给出逻辑
//   if (pwdEditForm.newPwd != pwdEditForm.confirmNewPwd) {
//     ElMessage.warning("新密码和确认密码不一致,请重新输入")
//     return
//   }
//   var loginUserStr = JSON.parse(localStorage.getItem("loginUser"))
//   axios.post(
//       server_url + "/servlet/user?method=doUpdatePwd",
//       "&id=" + loginUserStr.id +
//       "&userPassword=" + pwdEditForm.userPassword +
//       "&newPwd=" + pwdEditForm.newPwd
//   ).then(resp => {
//     if (resp.data.code == "00") {
//       ElMessage.success(resp.data.msg)
//       logout()
//     } else {
//       ElMessage.error(resp.data.msg)
//     }
//   }).catch(err => {
//     console.log(err)
//   })
// }
    function logout() {
      localStorage.removeItem("loginUser")
      router.push({path: '/login'})
    }

    onMounted(() => {
      const loginUserStr = localStorage.getItem('loginUser')
      if (loginUserStr) {
        const user = JSON.parse(loginUserStr)

        loginUser.role = user.role || {roleName: ''}
        loginUser.userName = user.userName || ''
        loginUser.userCode = user.userCode || ''
        loginUser.headUrl = user.headUrl || 'img/face.png'

        console.log("loginUser=" + loginUser)
        console.log("loginUser=" + loginUser.headUrl)

      }
    })
    return {
      iframeSrc,
      formLabelWidth,
      userEditFormVisible,
      userEditForm,
      userEditRef,
      userEditRules,
      showEditForm,
      pwdEditFormVisible,
      pwdEditForm,
      pwdEditFormRef,
      pwdEditRules,
      loginUser,
      requestUrl,
      handleEdit,
      handleAvatarSuccess,
      beforeAvatarUpload,
      doUpdateUser,
      submitUserUpdate,
      showEditPwdView,
      doUpdatePwd,
      logout,
      toHtml
    }
  }
}
</script>


<style scoped>
.el-header {
  background-color: #545c64;
}

.header-img {
  margin-top: 15px;
}

.face {
  margin-top: 5px;
  width: 40px;
  height: 40px;
  border-radius: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  color: whitesmoke;
  line-height: 60px;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.text {
  float: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}

.avatar {
  width: 78px;
  height: 78px;
  display: block;
}
</style>